package com.yy.QSManage.global;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域
 */
@Component
public class MyGlobalCorsConfig implements HandlerInterceptor {
    private static final String OPTIONS = "OPTIONS";

    public MyGlobalCorsConfig() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Authorization,Accept,apiKey,timestamp,sign,token,X-Requested-With,gridId");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Expose-Headers","refresh,Content-Disposition");    // 前端可以获取到的响应头
        response.setHeader("Content-Type","application/json");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(200);
        }
        RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
        return true;
    }
}
